<script setup lang="ts">
import type { LoginFormData, RegisterFormData } from '@/api/user/type'
import type { FormInstance } from 'element-plus'
import { register } from '@/api/user'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'

const router = useRouter()

const loginFormRef = ref<FormInstance>()

const loginFormData = ref<LoginFormData>({
  username: 'admin',
  password: '123456',
})

const loginRules = computed(() => ({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '请填写用户名',
    },
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: '请填写密码',
    },
    {
      min: 6,
      message: '密码长度不能小于6',
      trigger: 'blur',
    },
  ],
}))

async function handleLogin(formEl: FormInstance | undefined) {
  const useStore = useUserStore()
  if (!formEl)
    return
  try {
    const isValid = await formEl.validate()
    if (!isValid)
      return
    await useStore.doLogin(loginFormData.value)
    if (useStore.user) {
      ElMessage.success('登录成功！')
      router.push('/')
    }
    else {
      ElMessage.error('登录失败！')
    }
  }
  catch (error) {
    console.error('登录失败:', error)
  }
}

const registerFormRef = ref<FormInstance>()
const registerDialogVisible = ref(false)
const registerFormData = ref<RegisterFormData>({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
})

const registerRules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== registerFormData.value.password) {
          callback(new Error('两次输入密码不一致!'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
}))

async function handleRegister(formEl: FormInstance | undefined) {
  if (!formEl)
    return

  try {
    const isValid = await formEl.validate()
    if (!isValid)
      return
    register(registerFormData.value)
    registerDialogVisible.value = false
    ElMessage.success('注册成功！')
  }
  catch (error) {
    console.error('注册失败:', error)
    registerDialogVisible.value = true
  }
}

// 监听注册对话框的显示状态
watch(registerDialogVisible, (newVal) => {
  if (!newVal) {
    // 重置表单数据
    registerFormData.value = {
      username: '',
      password: '',
      confirmPassword: '',
      realName: '',
      phone: '',
    }
    // 清除表单验证（需要确保表单引用存在）
    registerFormRef.value?.resetFields()
  }
})
</script>

<template>
  <div class="login">
    <div class="login-header">
      <h1 class="system-title">
        <span class="gradient-text">鑫之冠</span>
        <span class="system-subtitle">运营管理平台</span>
      </h1>
      <div class="decorative-line" />
    </div>
    <el-form ref="loginFormRef" :model="loginFormData" :rules="loginRules" label-position="left" label-width="80px">
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="loginFormData.username"
          placeholder="admin"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="loginFormData.password"
          placeholder="123456"
          type="password"
          size="large"
          show-password
        />
      </el-form-item>
    </el-form>
    <div class="action-buttons">
      <el-button
        type="primary"
        size="large"
        @click="handleLogin(loginFormRef)"
      >
        登录
      </el-button>
      <el-button
        plain
        size="large"
        @click="registerDialogVisible = true"
      >
        注册
      </el-button>
    </div>
  </div>
  <el-dialog
    v-model="registerDialogVisible"
    title="用户注册"
    width="500px"
  >
    <el-form
      ref="registerFormRef"
      :model="registerFormData"
      :rules="registerRules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="registerFormData.username"
          placeholder="4-16位字母数字组合"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerFormData.password"
          type="password"
          show-password
          placeholder="至少6位字符"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerFormData.confirmPassword"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="registerFormData.realName"
          placeholder="请输入真实姓名"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="registerFormData.phone"
          placeholder="请输入联系方式"
        />
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="registerDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleRegister(registerFormRef)">
          提交注册
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use "sass:color";
.login {
  $primary: #409EFF;
  $text-primary: #303133;
  $text-regular: #606266;
  $border-color: #DCDFE6;
  $mobile-breakpoint: 768px;

  width: 100%;
  max-width: 420px;
  padding: 40px;
  background: #fff;
  border: 1px solid $border-color;
  border-radius: 6px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -60%);
  box-sizing: border-box;

  &-header {
    text-align: center;
    margin-bottom: 36px;

    .system-title {
      font-size: 26px;
      margin: 0 0 12px;
      letter-spacing: 2px;

      .gradient-text {
        background: linear-gradient(135deg, $primary, color.scale($primary, $lightness: 15%));
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        font-weight: 600;
      }

      .subtitle {
        font-size: 16px;
        color: $text-regular;
        margin-left: 10px;
        font-weight: 400;
      }
    }

    .decorative-line {
      width: 60px;
      height: 2px;
      background: $primary;
      margin: 0 auto;
      opacity: 0.8;
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    &__label {
      color: $text-regular;
      padding-bottom: 8px !important;
      font-size: 14px;
    }

    &__content {
      line-height: 1;
    }
  }

  .el-input {
    :deep(.el-input__wrapper) {
      border-radius: 4px;
      box-shadow: 0 0 0 1px $border-color inset;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 0 0 1px $primary inset;
      }

      &.is-focused {
        box-shadow: 0 0 0 2px $primary inset;
      }
    }
  }

  .el-button {
    width: 100%;
    border-radius: 4px;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }
  }

  @media (max-width: $mobile-breakpoint) {
    max-width: 90%;
    padding: 24px;
    border: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translate(-50%, -60%);

    &-header {
      .system-title {
        font-size: 22px;

        .subtitle {
          font-size: 14px;
          display: block;
          margin-left: 0;
          margin-top: 6px;
        }
      }

      .decorative-line {
        width: 40px;
      }
    }

    .el-form-item {
      margin-bottom: 20px;
    }
  }

  @keyframes float {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-6px); }
  }
}

.action-buttons {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 12px;

  .el-button {
    width: 100%;
    margin-left: 0;
  }

  .el-button--plain {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary-light-5);

    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid var(--el-border-color-light);
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
}

.dialog-footer {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
    max-width: 100%;
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
  }
}
</style>
